package com.cl.erp.auth;

import com.cl.erp.constant.CommonConstants;
import com.cl.erp.constant.ExceptionTextConstants;
import com.cl.erp.entity.AuthUser;
import com.cl.erp.entity.SysUser;
import com.cl.erp.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findOneByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(ExceptionTextConstants.USERNAME_NOT_FOUND);
        }
        return new AuthUser(sysUser.getUserId(),
                sysUser.getDeptId(),
                sysUser.getUsername(),
                sysUser.getPassword(),
                sysUser.getPhone(),
                true,
                true,
                true,
                !sysUser.getLockFlag().equals(CommonConstants.STATUS_LOCK),
                AuthorityUtils.createAuthorityList("admin")
        );
    }
}
